package com.huike.springboot1.demos.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        String uri = request.getRequestURI();
        // 放行 productList1.html
        if ("/productList1".equals(uri)) {
            return true;
        }

        // 检查是否登录，LoginController中的session存储数据，30分钟后过期
        Object loginUser = request.getSession().getAttribute("loginUser");
        if (loginUser == null) {
            // 未登录，跳转到登录页
            response.sendRedirect("/toLogin");
            return false;
        }

        return true;
    }
}
